package com.itlong.cloud.controller.property;

import com.alibaba.fastjson.JSON;
import com.itlong.cloud.POJO.DTO.property.*;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.DeviceMediaAttacheFileInfoVO;
import com.itlong.cloud.POJO.VO.property.DeviceMediaWallInfoVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.MediaTypeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.equip.property.IDeviceMediaWallServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import com.xuggle.xuggler.ICodec;
import com.xuggle.xuggler.IContainer;
import com.xuggle.xuggler.IStreamCoder;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * <desc>
 * 围墙机设备多媒体信息管理控制器
 * </desc>
 *
 * @createDate 2017-10-24
 */
@RestController
@RequestMapping("equip/deviceMediaWall")
public class DeviceMediaWallController extends DeviceMediaInfoController{

    @Autowired
    IDeviceMediaWallServiceClient iDeviceMediaWallServiceClient;  //围墙机设备多媒体信息服务接口协议提供对象.

    /**
     * <desc>
     *      保存单个围墙机设备多媒体信息
     * </desc>
     *
     * @param deviceMediaWallSaveForBrowserDTO  保存围墙机设备多媒体信息数据传输对象
     * @return 受影响的行数
     * @author Lix
     * @createDate 2017-10-24
     */
    @LoggerInfo(operateDesc = LogDescConstant.DEVICE_MEDIA_WALL_SAVE_LOG_DESC)
    @RequestMapping(path = "/save", method = RequestMethod.POST)
    @ResponseBody
    public Object saveDeviceMediaWallInfo(DeviceMediaWallSaveForBrowserDTO deviceMediaWallSaveForBrowserDTO,
                                         HttpServletRequest httpServletRequest) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            deviceMediaWallSaveForBrowserDTO = HttpProtocolUtil.parseRequestParamToDTO(DeviceMediaWallSaveForBrowserDTO.class, request);
            //判断参数合法性
            if (null == deviceMediaWallSaveForBrowserDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //多媒体标题合法性
            if (StringUtils.isBlank(deviceMediaWallSaveForBrowserDTO.getTitle())){
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_TITLE_NOT_EMPTY_ERR.getErrorCode());
            }
            if (deviceMediaWallSaveForBrowserDTO.getTitle().length() > PlatformConstants.MEDIA_TITLE_MAX_LENGTH){
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_TITLE_TOO_LONG_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(deviceMediaWallSaveForBrowserDTO.getBindDeviceInfos())){
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_WALL_BIND_DEVICE_EMPTY_ERR.getErrorCode());
            }
            Integer mediaType = deviceMediaWallSaveForBrowserDTO.getType();
            if (!NumberHandlerUtil.isInRange(mediaType,MediaTypeEnum.TEXT.getType(),MediaTypeEnum.VIDEO.getType())){
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_SORT_INVALID_ERR.getErrorCode());
            }
            //将页面传入的多媒体资源数据部分属性转换为内部对象属性
            DeviceMediaWallSaveDTO deviceMediaWallSaveDTO = new DeviceMediaWallSaveDTO();
            BeanUtils.copyProperties(deviceMediaWallSaveForBrowserDTO, deviceMediaWallSaveDTO);
            if (deviceMediaWallSaveDTO.getStatus() == null){
                deviceMediaWallSaveDTO.setStatus(DataStatusEnum.NORMAL.getType());
            }
            //分析围墙机多媒体资源绑定的设备列表
            List<DeviceMediaBindDeviceDTO> deviceMediaBindDeviceDTOS = null;
            try {
                deviceMediaBindDeviceDTOS = JSON.parseArray(deviceMediaWallSaveForBrowserDTO.getBindDeviceInfos(),
                        DeviceMediaBindDeviceDTO.class);
            } catch (Exception e) {
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_BIND_DEVICE_INVALID_ERR.getErrorCode());
            }
            if ((null == deviceMediaBindDeviceDTOS) || (deviceMediaBindDeviceDTOS.isEmpty())){
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_WALL_BIND_DEVICE_EMPTY_ERR.getErrorCode());
            }
            deviceMediaWallSaveDTO.setBindDeviceInfos(deviceMediaBindDeviceDTOS);

            //上传多媒体资源附件（图片\视频）
            if (mediaType != MediaTypeEnum.TEXT.getType()){
                boolean isMultipart = ServletFileUpload.isMultipartContent(httpServletRequest);
                if (!isMultipart) {
                    //是否是带文件上传的表单
                    return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_RESOURCE_EMPTY_ERR.getErrorCode());
                }
                MessageVO messageVO = this.upLoadMediaFileForSave(httpServletRequest,deviceMediaWallSaveDTO);
                if (null != messageVO)
                {
                    return messageVO;
                }
            }else {
                if (StringUtils.isBlank(deviceMediaWallSaveForBrowserDTO.getContent())){
                    return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_TEXT_NOT_EMPTY_ERR.getErrorCode());
                }
                if (deviceMediaWallSaveForBrowserDTO.getContent().length() > PlatformConstants.MEDIA_TEXT_MAX_LENGTH){
                    return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_TEXT_TOO_LONG_ERR.getErrorCode());
                }
            }
            //添加单个围墙机设备多媒体信息
            iDeviceMediaWallServiceClient.saveDeviceMediaWallInfo(deviceMediaWallSaveDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }
        catch (Exception e){
            throw new DataAccessException("【物业_多媒体_围墙机多媒体信息】添加围墙机多媒体信息失败", e);
        }
    }

    /**
     * <desc>
     *     修改单个围墙机设备多媒体信息【根据多媒体Id（mediaId）】
     * </desc>
     *
     * @param deviceMediaWallUpdateForBrowserDTO 修改围墙机设备多媒体信息数据传输对象
     * @return 受影响的行数
     * @author Lix
     * @createDate 2017-10-24
     */
    @LoggerInfo(operateDesc = LogDescConstant.DEVICE_MEDIA_WALL_UPDATE_LOG_DESC)
    @RequestMapping(path = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object updateDeviceMediaInfo(DeviceMediaWallUpdateForBrowserDTO deviceMediaWallUpdateForBrowserDTO,
                                           HttpServletRequest httpServletRequest) {
        try {
            deviceMediaWallUpdateForBrowserDTO = HttpProtocolUtil.parseRequestParamToDTO(DeviceMediaWallUpdateForBrowserDTO.class, httpServletRequest);

            //判断参数合法性
            if (null == deviceMediaWallUpdateForBrowserDTO) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //多媒体标题合法性
            if (StringUtils.isBlank(deviceMediaWallUpdateForBrowserDTO.getTitle())){
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_TITLE_NOT_EMPTY_ERR.getErrorCode());
            }
            if (deviceMediaWallUpdateForBrowserDTO.getTitle().length() > PlatformConstants.MEDIA_TITLE_MAX_LENGTH){
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_TITLE_TOO_LONG_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(deviceMediaWallUpdateForBrowserDTO.getBindDeviceInfos())){
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_WALL_BIND_DEVICE_EMPTY_ERR.getErrorCode());
            }
            Integer mediaType = deviceMediaWallUpdateForBrowserDTO.getType();
            if (!NumberHandlerUtil.isInRange(mediaType,MediaTypeEnum.TEXT.getType(),MediaTypeEnum.VIDEO.getType())){
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_SORT_INVALID_ERR.getErrorCode());
            }

            //将页面传入的多媒体资源数据部分属性转换为内部对象属性
            DeviceMediaWallUpdateDTO deviceMediaWallUpdateDTO = new DeviceMediaWallUpdateDTO();
            BeanUtils.copyProperties(deviceMediaWallUpdateForBrowserDTO, deviceMediaWallUpdateDTO);

            //分析围墙机多媒体资源绑定的设备列表
            List<DeviceMediaBindDeviceDTO> deviceMediaBindDeviceDTOS = JSON.parseArray(deviceMediaWallUpdateForBrowserDTO.getBindDeviceInfos(),
                    DeviceMediaBindDeviceDTO.class);
            if ((null == deviceMediaBindDeviceDTOS) || (deviceMediaBindDeviceDTOS.isEmpty())){
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_WALL_BIND_DEVICE_EMPTY_ERR.getErrorCode());
            }
            deviceMediaWallUpdateDTO.setBindDeviceInfos(deviceMediaBindDeviceDTOS);

            DeviceMediaWallInfoVO oldDeviceMediaWallInfoVO = iDeviceMediaWallServiceClient.getOneMediaWallInfo(
                    deviceMediaWallUpdateDTO.getMediaId());
            if (null == oldDeviceMediaWallInfoVO){
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_NOT_EXISTS_ERR.getErrorCode());
            }

            //上传多媒体资源附件（图片\视频）
            if (mediaType != MediaTypeEnum.TEXT.getType()){
                boolean isMultipart = ServletFileUpload.isMultipartContent(httpServletRequest);
                if (!isMultipart) {
                    //是否是带文件上传的表单
                    return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_RESOURCE_EMPTY_ERR.getErrorCode());
                }

                MessageVO messageVO = this.upLoadMediaFileForUpdate(httpServletRequest,deviceMediaWallUpdateDTO,oldDeviceMediaWallInfoVO);
                if (null != messageVO)
                {
                    return messageVO;
                }
            }else {
                if (StringUtils.isBlank(deviceMediaWallUpdateForBrowserDTO.getContent())){
                    return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_TEXT_NOT_EMPTY_ERR.getErrorCode());
                }
                if (deviceMediaWallUpdateForBrowserDTO.getContent().length() > PlatformConstants.MEDIA_TEXT_MAX_LENGTH){
                    return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_TEXT_TOO_LONG_ERR.getErrorCode());
                }
            }

            //修改单个围墙机设备多媒体信息
            iDeviceMediaWallServiceClient.updateDeviceMediaInfo(deviceMediaWallUpdateDTO);
            return new MessageVO(deviceMediaWallUpdateForBrowserDTO.getMediaId(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }
        catch (Exception e){
            throw new DataAccessException("【物业_多媒体_围墙机多媒体信息】修改围墙机多媒体信息失败", e);
        }
    }

    /**
     * <desc>
     *      精确查询，获取单个设备多媒体信息【根据多媒体Id（mediaId）】
     * </desc>
     * @param mediaId 多媒体Id
     * @return  单个设备多媒体信息结果对象
     * @author Lix
     * @createDate 2017-10-23
     */
    @RequestMapping(path = "/getOne", method = RequestMethod.POST)
    @ResponseBody
    public Object getOneDeviceMediaInfo(String mediaId) {
        MessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            mediaId = request.getAttribute("mediaId") == null ? null : request.getAttribute("mediaId").toString();
            //多媒体Id不能为空
            if (StringUtils.isBlank(mediaId)) {
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIAID_NOT_NULL.getErrorCode());
            }
            //查询单个设备多媒体信息
            DeviceMediaWallInfoVO deviceMediaWallInfoVO = iDeviceMediaWallServiceClient.getOneMediaWallInfo(mediaId);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), deviceMediaWallInfoVO);
        } catch (Exception e) {
            throw new DataAccessException("【物业_多媒体_围墙机多媒体信息】精确查询单个围墙机多媒体信息失败", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *    删除围墙机多媒体资源关联的部分设备关系. .
     * </desc>
     *
     * @param deviceMediaRemoveWallBindDeviceForBrowerDTO 待删除的围墙机多媒体与设备之间的关系
     * @return MessageVO 标准格式化响应结果
     * @author LewisLouis
     * @createDate 2017-11-23
     */
    @LoggerInfo(operateDesc = LogDescConstant.DEVICE_MEDIA_REMOVE_DEVICE_LOG_DESC)
    @RequestMapping(path = "/removeBindDevices", method = RequestMethod.POST)
    @ResponseBody
    public Object removeBindDevices(DeviceMediaRemoveWallBindDeviceForBrowerDTO deviceMediaRemoveWallBindDeviceForBrowerDTO) {
        MessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            deviceMediaRemoveWallBindDeviceForBrowerDTO = HttpProtocolUtil.parseRequestParamToDTO(DeviceMediaRemoveWallBindDeviceForBrowerDTO.class, request);
            if (null == deviceMediaRemoveWallBindDeviceForBrowerDTO){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //多媒体Id不能为空
            if (StringUtils.isBlank(deviceMediaRemoveWallBindDeviceForBrowerDTO.getMediaId())) {
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIAID_NOT_NULL.getErrorCode());
            }
            DeviceMediaRemoveWallBindDeviceDTO deviceMediaRemoveWallBindDeviceDTO = new DeviceMediaRemoveWallBindDeviceDTO();
            BeanUtils.copyProperties(deviceMediaRemoveWallBindDeviceForBrowerDTO, deviceMediaRemoveWallBindDeviceDTO);

            if (StringUtils.isBlank(deviceMediaRemoveWallBindDeviceForBrowerDTO.getRemoveDevices())){
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_WALL_BIND_DEVICE_EMPTY_ERR.getErrorCode());
            }
            List<String> deviceUniques = Arrays.asList(deviceMediaRemoveWallBindDeviceForBrowerDTO.getRemoveDevices().split(","));
            List<DeviceMediaBindDeviceDTO> deviceMediaBindDeviceDTOS = new ArrayList<>();
            for (String deviceUnique:deviceUniques){
               DeviceMediaBindDeviceDTO deviceMediaBindDeviceDTO = new DeviceMediaBindDeviceDTO();
               deviceMediaBindDeviceDTO.setDeviceUnique(deviceUnique);
               deviceMediaBindDeviceDTOS.add(deviceMediaBindDeviceDTO);
           }

            deviceMediaRemoveWallBindDeviceDTO.setRemoveDevices(deviceMediaBindDeviceDTOS);
            //查询单个设备多媒体信息
            iDeviceMediaWallServiceClient.removeMediaWallRelation(deviceMediaRemoveWallBindDeviceDTO);
            messageVO = new MessageVO(deviceMediaRemoveWallBindDeviceForBrowerDTO.getMediaId(),BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_多媒体_围墙机多媒体信息】删除围墙机多媒体信息关联的设备失败", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *    上传多媒体资源到Http服务器.
     * </desc>
     *
     * @param httpServletRequest 请求到Http对象
     *   @param deviceMediaWallSaveDTO 待保存到多媒体信息对象
     * @return null 上传成功 or  MessageVO 上传失败的错误信息
     * @author LewisLouis
     * @createDate 2017-11-20
     */
    private MessageVO upLoadMediaFileForSave(HttpServletRequest httpServletRequest,DeviceMediaWallSaveDTO deviceMediaWallSaveDTO) throws IOException
    {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) httpServletRequest;
        StringBuffer attacheFileUrls = new StringBuffer();
        StringBuffer attacheFiles = new StringBuffer();
        StringBuffer attacheFileMd5s = new StringBuffer();
        Map<String,MultipartFile> multipartFileMap = multipartRequest.getFileMap();
        if (multipartFileMap.isEmpty()){
            return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_RESOURCE_EMPTY_ERR.getErrorCode());
        }
        for (String fileKey : multipartFileMap.keySet()) {
            List<MultipartFile> fileList = multipartRequest.getFiles(fileKey);
            Iterator<MultipartFile> fileIter = fileList.iterator();
            while (fileIter.hasNext()) {
                MultipartFile mediaFile = fileIter.next();
                String fileName = mediaFile.getOriginalFilename();
                InputStream fileStream = mediaFile.getInputStream();
                ByteArrayOutputStream streamForClone = cloneInputStream(fileStream);
                String fileMd5;
                String fileUrl;

                try {
                    //若是图片，真正类型必须是PNG
                    if (deviceMediaWallSaveDTO.getType().equals(String.valueOf(MediaTypeEnum.IMGAE.getType()))){
                        InputStream checkStream = new ByteArrayInputStream(streamForClone.toByteArray());
                        try {
                            ImageInputStream iis = ImageIO.createImageInputStream(checkStream);
                            Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis);
                            while (imageReaders.hasNext()) {
                                ImageReader reader = imageReaders.next();
                                if (!StringHandlerUtil.compareStrIgnoreCaseWithOutEmpty(reader.getFormatName(),"png")){
                                    return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_IMAGE_TYPE_INVALID_ERR.getErrorCode());
                                }
                            }
                        } finally {
                            checkStream.close();
                        }
                    }
                    InputStream upLoadStream = new ByteArrayInputStream(streamForClone.toByteArray());
                    InputStream cloneStream = new ByteArrayInputStream(streamForClone.toByteArray());
                    try {
                        fileMd5 = DigestUtils.md5Hex(cloneStream);
                        fileUrl = this.uploadFile(upLoadStream, fileName);

                        //若是视频，需要获取其真正的分辨率
                        if (MediaTypeEnum.VIDEO.getType().equals(deviceMediaWallSaveDTO.getType())) {
                            MessageVO analysisMessage = videoAnalysis(fileUrl);
                            if (analysisMessage != null) {
                                return analysisMessage;
                            }
                        }

                    } finally {
                        cloneStream.close();
                        upLoadStream.close();
                    }
                } finally {
                    streamForClone.close();
                }

                if (StringUtils.isBlank(fileUrl)) {
                    return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_UPLOAD_ERR.getErrorCode());
                }

                if (attacheFileUrls.length() <= 0) {
                    attacheFileUrls.append(fileUrl);
                    attacheFiles.append(fileName);
                    attacheFileMd5s.append(fileMd5);
                } else {
                    attacheFileUrls.append(",").append(fileUrl);
                    attacheFiles.append(",").append(fileName);
                    attacheFileMd5s.append(",").append(fileMd5);
                }
            }
        }
        deviceMediaWallSaveDTO.setAttacheFiles(attacheFiles.toString());
        deviceMediaWallSaveDTO.setAttacheFileUrls(attacheFileUrls.toString());
        deviceMediaWallSaveDTO.setAttacheFileMd5(attacheFileMd5s.toString());
        return null;
    }

    /**
     * <desc>
     *    更新上传多媒体资源到Http服务器.
     * </desc>
     *
     * @param httpServletRequest 请求到Http对象
     *   @param deviceMediaWallUpdateDTO 待更新保存的多媒体信息对象
     * @return null 上传成功 or  MessageVO 上传失败的错误信息
     * @author LewisLouis
     * @createDate 2017-11-22
     */
    private MessageVO upLoadMediaFileForUpdate(HttpServletRequest httpServletRequest,
                                             DeviceMediaWallUpdateDTO deviceMediaWallUpdateDTO,
                                             DeviceMediaWallInfoVO oldDeviceMediaWallInfoVO) throws IOException
    {

        List<DeviceMediaAttacheFileInfoVO> oldAttacheFiles = oldDeviceMediaWallInfoVO.getAttacheFiles();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) httpServletRequest;
        StringBuffer attacheFileUrls = new StringBuffer();
        StringBuffer attacheFiles = new StringBuffer();
        StringBuffer attacheFileMd5s = new StringBuffer();

        //第一步查看哪些附件没有变更
        for (DeviceMediaAttacheFileInfoVO oneOldDeviceMediaAttacheFileInfoVO:oldAttacheFiles){
            String attacheFileUrl = httpServletRequest.getParameter(oneOldDeviceMediaAttacheFileInfoVO.getFileName());
            if (StringHandlerUtil.compareStrIgnoreCaseWithOutEmpty(attacheFileUrl,oneOldDeviceMediaAttacheFileInfoVO.getAttacheFileUrl())){
                if (attacheFileUrls.length() <= 0) {
                    attacheFileUrls.append(oneOldDeviceMediaAttacheFileInfoVO.getAttacheFileUrl());
                    attacheFiles.append(oneOldDeviceMediaAttacheFileInfoVO.getFileName());
                    attacheFileMd5s.append(oneOldDeviceMediaAttacheFileInfoVO.getFileMd5());
                } else {
                    attacheFileUrls.append(",").append(oneOldDeviceMediaAttacheFileInfoVO.getAttacheFileUrl());
                    attacheFiles.append(",").append(oneOldDeviceMediaAttacheFileInfoVO.getFileName());
                    attacheFileMd5s.append(",").append(oneOldDeviceMediaAttacheFileInfoVO.getFileMd5());
                }

            }
        }

        //第二步查看新上传了哪些附件
        Map<String,MultipartFile> multipartFileMap = multipartRequest.getFileMap();
        if (multipartFileMap.isEmpty() && (attacheFileUrls.length() < 0)){
            return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_RESOURCE_EMPTY_ERR.getErrorCode());
        }
        for (String fileKey : multipartFileMap.keySet()) {
            List<MultipartFile> fileList = multipartRequest.getFiles(fileKey);
            Iterator<MultipartFile> fileIter = fileList.iterator();
            while (fileIter.hasNext()) {
                MultipartFile mediaFile = fileIter.next();
                String fileName = mediaFile.getOriginalFilename();
                InputStream fileStream = mediaFile.getInputStream();
                ByteArrayOutputStream streamForClone = cloneInputStream(fileStream);
                String fileMd5;
                String fileUrl;
                try {
                    if (deviceMediaWallUpdateDTO.getType() == MediaTypeEnum.IMGAE.getType()){
                        InputStream checkStream = new ByteArrayInputStream(streamForClone.toByteArray());
                        try {
                            ImageInputStream iis = ImageIO.createImageInputStream(checkStream);
                            Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis);
                            while (imageReaders.hasNext()) {
                                ImageReader reader = imageReaders.next();
                                if (!StringHandlerUtil.compareStrIgnoreCaseWithOutEmpty(reader.getFormatName(),"png")){
                                    return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_IMAGE_TYPE_INVALID_ERR.getErrorCode());
                                }
                            }
                        } finally {
                            checkStream.close();
                        }
                    }
                    InputStream upLoadStream = new ByteArrayInputStream(streamForClone.toByteArray());
                    InputStream cloneStream = new ByteArrayInputStream(streamForClone.toByteArray());
                    try {
                        fileMd5 = DigestUtils.md5Hex(cloneStream);
                        DeviceMediaAttacheFileInfoVO deviceMediaAttacheFileInfoVO = getAttacheFileInfoByMD5(fileMd5,oldAttacheFiles);
                        if (null == deviceMediaAttacheFileInfoVO){
                            fileUrl = this.uploadFile(upLoadStream, fileName);
                            if (StringUtils.isBlank(fileUrl)) {
                                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_UPLOAD_ERR.getErrorCode());
                            }

                            //若是视频，需要获取其真正的分辨率
                            if (MediaTypeEnum.VIDEO.getType().equals(deviceMediaWallUpdateDTO.getType())) {
                                MessageVO analysisMessage = videoAnalysis(fileUrl);
                                if (analysisMessage != null) {
                                    return analysisMessage;
                                }
                            }

                        } else {
                            fileUrl = deviceMediaAttacheFileInfoVO.getAttacheFileUrl();
                        }
                    } finally {
                        cloneStream.close();
                        upLoadStream.close();

                    }
                } finally {
                    streamForClone.close();
                }
                if (attacheFileUrls.length() <= 0) {
                    attacheFileUrls.append(fileUrl);
                    attacheFiles.append(fileName);
                    attacheFileMd5s.append(fileMd5);
                } else {
                    attacheFileUrls.append(",").append(fileUrl);
                    attacheFiles.append(",").append(fileName);
                    attacheFileMd5s.append(",").append(fileMd5);
                }
            }
        }
        deviceMediaWallUpdateDTO.setAttacheFiles(attacheFiles.toString());
        deviceMediaWallUpdateDTO.setAttacheFileUrls(attacheFileUrls.toString());
        deviceMediaWallUpdateDTO.setAttacheFileMd5(attacheFileMd5s.toString());
      return null;
    }

    /**
     * <desc>
     *      多媒体视频解析
     * <desc/>
     * @param  fileUrl  视频的链接地址
     * @return 标准化响应结果
     * @author Biao.R
     * @createDate 2018/1/16
     */
    private MessageVO videoAnalysis(String fileUrl) {
        //创建Xuggle容器
        IContainer container = IContainer.make();
        if (container.open(fileUrl, IContainer.Type.READ, null) < 0) {
            return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_TYPE_IS_NOT_VIDEO.getErrorCode());
        }
        int numStreams = container.getNumStreams();
        for (int i = 0; i < numStreams; i++) {
            IStreamCoder coder = container.getStream(i).getStreamCoder();
            //视频分辨率校验
            if (coder.getHeight() > 768 || coder.getWidth() > 1366) {
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_VIDEO_RESOLUTION_RATIO_BEYOND.getErrorCode());
            }
            //视频格式校验
            if (ICodec.Type.CODEC_TYPE_VIDEO.equals(coder.getCodecType())
                    && PlatformConstants.MEDIA_PAGE_PLAY_VIDEO_SUPPORT_FORMAT.indexOf(String.valueOf(coder.getCodecID()).toUpperCase()) == -1) {
                return new MessageVO(PropertyErrorCodeEnum.EQUIP_MEDIA_VIDEO_FORMAT_NOT_SUPPORT.getErrorCode());
            }
        }
        return null;
    }
}
